package com.vrsys.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.vrsys.domain.session.Account;
import com.vrsys.service.AccountService;
import com.vrsys.util.Constants;

@Controller
@RequestMapping("/account")
public class AccountController extends BaseController {
    @Autowired
    private AccountService accountService;
    /*
     * This is Ajax calling
     */
    @RequestMapping(value = "/authaccount1.od",method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public void authAccount(@RequestBody Account account) {
        if (accountService.authAccount(account))
            logger.info("user " + account.getUserName() + " authorized.");
        else
            logger.info("invalid user " + account.getUserName());
    }

    @RequestMapping(value = "/authaccount.od", method = RequestMethod.POST)
    public String authAccount1(@RequestParam("weChatId") String weChatId, HttpSession session) {

        Account acct = (Account) session.getAttribute(Constants.SESSION_ACCOUNT_LABLE);
        if(null != acct && acct.isLogged())
            return "redirect:/product/products.od";

        Account account = new Account();
        account.setWeChatId(weChatId);

        if (accountService.authAccount(account)) {
            logger.info("user " + account.getWeChatId() + " authorized.");
        } else {
            logger.info("invalid user " + account.getUserName());
            accountService.addAccount(account);
        }
        account = accountService.queryAccount(account);
        account.setLogged(true);
        session.setAttribute(Constants.SESSION_ACCOUNT_LABLE, account);
        return "redirect:/product/products.od";
    }

    @RequestMapping(value = "/logoutaccount.od",method = {RequestMethod.POST,RequestMethod.GET})
    public String logoutAccount(HttpSession session) {
        session.setAttribute(Constants.SESSION_ACCOUNT_LABLE, null);
        return "redirect:/index";
    }
}
